package com.cuxiaoyi.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.NamingException;

import com.cuxiaoyi.Constants;
import com.cuxiaoyi.db.Dao;
import com.cuxiaoyi.model.ItemsFilter;
import com.cuxiaoyi.taobao.TaobaoProxy;
import com.cuxiaoyi.utils.PagingOption;
import com.cuxiaoyi.utils.PagingResult;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.SellerCat;
import com.taobao.api.request.TimeGetRequest;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.SellercatsListGetResponse;
import com.taobao.api.response.TimeGetResponse;

public class ItemsAction extends ActionSupport implements Constants{

	static Logger _log = Logger.getLogger(ItemsAction.class.getName());
	
	private ItemsFilter filter;
	private PagingOption option;
	private PagingResult<com.cuxiaoyi.model.Item> pagingItems;
	private List<SellerCat> categories;
	private Date now;
	
	public String execute() throws Exception {
		if (option == null)
		{
			option = new PagingOption();
			option.setLimit(30);
		}
		if (filter == null)
		{
			filter = new ItemsFilter();
		}
		Map<String, Object> session = ActionContext.getContext().getSession();
		String sessionId = (String)session.get(TOP_SESSION);
		long userId = Long.parseLong((String)session.get(USER_ID));
		_log.info("filter: " + filter);
		Map<Long, com.cuxiaoyi.model.Item> promotedItems = Dao.INSTANCE.getPromotedItems(userId);
		if (filter.getSaleStatus() == ItemsFilter.STATUS_ONSALE)
		{
			ItemsOnsaleGetResponse rsp = TaobaoProxy.getOnSales(sessionId, 
					option.getCurrentPage() + 1, option.getLimit(), filter.getSellerCids(), filter.getKeyWord());
			if (rsp.isSuccess())
			{
				_log.info("total: " + rsp.getTotalResults());
				List<Item> items = rsp.getItems();
				_log.info("got: " + (items == null ? 0 : items.size()));
				List<com.cuxiaoyi.model.Item> promotionItems = getItems(items, promotedItems);
				pagingItems = new PagingResult<com.cuxiaoyi.model.Item>();
				pagingItems.setItems(promotionItems);
				pagingItems.setOption(option);
				pagingItems.setTotal(rsp.getTotalResults());
			}
			else
			{
				error(rsp);
			}
		}
		else
		{
			ItemsInventoryGetResponse rsp = TaobaoProxy.getInventory(sessionId, 
					option.getCurrentPage() + 1, option.getLimit(), null, filter.getSellerCids(), filter.getKeyWord());
			if (rsp.isSuccess())
			{
				_log.info("total: " + rsp.getTotalResults());
				List<Item> items = rsp.getItems();
				_log.info("got: " + (items == null ? 0 : items.size()));
				List<com.cuxiaoyi.model.Item> promotionItems = getItems(items, promotedItems);
				pagingItems = new PagingResult<com.cuxiaoyi.model.Item>();
				pagingItems.setItems(promotionItems);
				pagingItems.setOption(option);
				pagingItems.setTotal(rsp.getTotalResults());
			}
			else
			{
				error(rsp);
			}
		}
		retriveCategories();
		return SUCCESS;
	}
	
	private List<com.cuxiaoyi.model.Item> getItems(List<Item> items, Map<Long, com.cuxiaoyi.model.Item> promotedItems) throws NamingException, SQLException
	{
		if (now == null)
		{
			now = getTaobaoTime();
			_log.info("taobao.time: " + now);
		}
		List<com.cuxiaoyi.model.Item> promoteItems = new ArrayList<com.cuxiaoyi.model.Item>();
		if (items != null)
		{
			for (Item item : items)
			{
				com.cuxiaoyi.model.Item i = promotedItems.remove(item.getNumIid());
				if (i == null)
				{
					i = new com.cuxiaoyi.model.Item();
					i.setNumIid(item.getNumIid());
				}
				i.setPicUrl(item.getPicUrl());
				i.setTitle(item.getTitle());
				i.setPrice(item.getPrice());
				i.setStatus(getStatus(i));
				promoteItems.add(i);
			}
		}
		return promoteItems;
	}
	
	private Date getTaobaoTime()
	{
		TimeGetRequest req = new TimeGetRequest();
		try {
			TimeGetResponse rsp = TaobaoProxy.getClient().execute(req);
			return rsp.getTime();
		} catch (ApiException e) {
			_log.log(Level.WARNING, "", e);
		}
		return null;
	}
	
	private void retriveCategories() throws ApiException
	{
		Map<String, Object> session = ActionContext.getContext().getSession();
		String nick = (String)session.get(USER);
		SellercatsListGetResponse catRsp = TaobaoProxy.getSellerCategories(nick);
		categories = catRsp.getSellerCats();
//		SellerCat root = new SellerCat();
//		root.setCid(0L);
//		root.setName("全部");
//		root.setParentCid(-1L);
//		Map<Long, SellerCategory> map = new HashMap<Long, SellerCategory>();
//		map.put(root.getCid(), new SellerCategory(root));
//		for (SellerCat cat : categories)
//		{
//			SellerCategory c = new SellerCategory(cat);
//			map.put(cat.getCid(), c);
//		}
//		for (Map.Entry<Long, SellerCategory> entry : map.entrySet())
//		{
//			SellerCategory c = entry.getValue();
//			Long parentCid = c.getCategory().getParentCid();
//			SellerCategory parent = map.get(parentCid);
//			c.setParent(parent);
//		}
//		categoryTree = map.get(0);
//		ActionContext.getContext().put("category", categoryTree);
	}
	
	public PagingResult<com.cuxiaoyi.model.Item> getPagingItems()
	{
		return pagingItems;
	}

	public void setFilter(ItemsFilter filter) {
		this.filter= filter;
	}

	public ItemsFilter getFilter() {
		return filter;
	}
	
	public void setOption(PagingOption option) {
		this.option = option;
	}

	public PagingOption getOption() {
		return option;
	}
	
	public List<SellerCat> getCategories() {
		return categories;
	}
	
	private void error(TaobaoResponse rsp)
	{
		_log.info(rsp.getErrorCode() + " - " + rsp.getMsg() + " - " + rsp.getSubCode() + " - " + rsp.getSubMsg());
	}
	
	public short getStatus(com.cuxiaoyi.model.Item item)
	{
		Date start = item.getStartDate();
		Date end = item.getEndDate();
		if (end != null && now != null)
		{
			if (now.before(start))
			{
				return com.cuxiaoyi.model.Item.STATUS_NOT_STARTED;
			}
			if (now.after(start) && now.before(end))
			{
				return com.cuxiaoyi.model.Item.STATUS_PROMOTING;
			}
			if (now.after(end))
			{
				return com.cuxiaoyi.model.Item.STATUS_OUT_OF_DATE;
			}
		}
		return 0;
	}
}
